import copy

import allure

from lib.core.dbase import MySqlClient


@allure.step('执行assert_all_case方法，断言[{assert_type}]类型内所有表达式.')
def assert_all_case(response, assert_type, value):
    """
    解析响应,断言
    :param response:
    :param assert_type: 断言类型
    :param value:
    :return:
    """
    # 深拷贝，只复制值
    res = copy.deepcopy(response)
    # json()函数，转为json属性
    try:
        res.json = res.json()
    except Exception:
        res.json = {'msg': 'Response not json data'}
    # assert_msg：断言描述，例如：断言状态码为200
    # expect_actual: 预期结果和实际结果
    for assert_msg, expect_actual in value.items():
        # print(assert_msg, expect_actual)
        # 预期结果
        expect = expect_actual[0]
        # 实际结果
        actual = expect_actual[1]
        # 反射取值
        try:
            actual_value = getattr(res, actual)
        except Exception as e:
            # raise AssertionError(f'yaml中response属性不存在:{actual},')
            actual_value = actual

        # match 等同于java中的switch case
        match assert_type:
            case "equals":
                if assert_msg == "code":
                    assert_info = f"状态码不一致断言失败，预期为：{expect},实际为：{actual_value}"
                else:
                    assert_info = assert_msg
                assert expect == actual_value, assert_info
            case "contains":
                assert expect in actual_value, assert_msg
            case "db":
                # 预期结果，执行sql
                sql = MySqlClient().execute_sql(expect)
                # 预期结果 与 response.text,实际结果
                # 从元组中获取值
                assert sql[0] in actual_value, assert_msg
